﻿var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var compress = require('compression');
var fs = require('fs');
var Wechat = require('./wechat.js');
var cookieParser=require("cookie-parser");
var admin =require('./routes/admin.js');
var Oracledb=require("./db/Oracledb.js");
var Msdb=require("./db/Msdb.js");
const jwt= require('jsonwebtoken');
const expressJwt = require('express-jwt');
const nodeExcel = require('excel-export');
var Excel = require('exceljs');
var Redisdb=require("./db/Redisdb.js");
const log = require('./logger');
var logger = require('./logger').logger;
const crypto = require('crypto');
var Mysqldb = require('./db/Mysqldb.js');
var request=require("request");
const nodemailer = require('nodemailer');//对nodemailer模块进行导入
const { getSyndevicedata } = require("./shzt.js");
const schedule = require('node-schedule');
const { xm_fb, xm_ybjz, xm_kb, update_gysjb, update_gysjb_pm, xm_xbjz, update_gysbqxj, xm_tbkz, xm_tbjz, xm_pbjz } = require('./routes/adminroute/shipSRM/chmes_sys_ddd_util.js');
const DingTalk = require('./dingtalk.js');

const secret = 'cxcx';

log.use(app);
//手动记录，可以代替console.log
logger.info('test info 1');

// app.use(function(req,res,next){  
//     console.log("referer---"+req.headers.referer);  
//     if(req.headers.referer!="http://yunqiao.sserbpo.com/manage/"||req.headers.referer!="http://yunqiao.sserbpo.com/"||req.headers.referer!="http://localhost:7788/"||req.headers.referer!="http://47.98.191.71"
//       ||req.headers.referer!="http://47.98.191.71:8089"||req.headers.referer!="http://yunqiao.sserbpo.com:8089")
//     { console.log("referer可信")    
   
//       next(); 
// }
//   else{ 
//     console.log("referer不可信")
//       res.status(401).send('无效referer');  
//    }
  
  
// });  

app.use(compress());
app.use(express.static("../opt"));

app.use(express.static("dist"));
app.use(express.static("dist2"));
app.use(express.static("dist-cache"));
app.use(express.static("public"));

app.use(express.static("uploads"));
app.use(bodyParser.json({limit: '50mb'})); // for parsing application/json
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
app.use(cookieParser());


app.use(function (err, req, res, next) {
    //当token验证失败时会抛出如下错误
 
    if (err.name === 'UnauthorizedError') {   
        //这个需要根据自己的业务逻辑来处理（ 具体的err值 请看下面）
console.log("无效权限")
console.log("err  "+JSON.stringify(err))
    res.status(401).send('invalid token...');
    }
});

//路由模块化
app.use('/admin',admin); 







app.get('/api/auth', async function (req, res) {
  //console.log('来了一次访问');
  var wechat=new Wechat();
  const rtobj= await wechat.auth(req, res);

  console.log("openid--"+rtobj.openid);
  var loherf=`http://www.0574link.com?openid=${rtobj.openid}`;
  console.log("loherf--"+loherf)
  res.writeHead(302,{
    'Location': loherf
  })
  console.log(res._header);
  res.end();

})





//拉入黑名单
async function checkhmd(){
  var db=new Msdb();

  var ddd=`select  * from qw_jcjl where DATEDIFF(hour, cqsj, jrsj)>12 or  cqsj is null or DateName(hour,cqsj)>21
`
  
}


//测试邮箱
async function sendemailtoadmin(text){
  var user = '1584824430@qq.com' //自己的邮箱
  var pass = "oppnaqohqyiwhiif" //qq邮箱的授权码
  var recipient = '1584824430@qq.com' //接收人邮箱
  let transporter = nodemailer.createTransport({
    host:'smtp.qq.com',
    port:587,
    secure: false,
    auth:{
      user:user,
      pass:pass
    }
  })
  let info = await transporter.sendMail({
    from: `发送人<${user}>`,
    to: `接收人<${recipient }>`,
    subject: '名字',
    text:text //发送邮箱的内容
  })
}

function format (bytes) { 
  return (bytes/1024/1024).toFixed(2)+'MB'; 
};





var server = app.listen(2233, async function () {
  var host = 'localhost'
  var port = server.address().port 
  console.log("应用实例，访问地址为 http://%s:%s", host, port);
   // var db=new Mysqldb("fsdfsdfsdf");

   logger.info("最大配置内存为"+require("v8").getHeapStatistics().total_available_size / 1024 / 1024)



//内存监控监控
   var memhealth=setInterval(() => {
      var  mem = process.memoryUsage();
      if(mem.heapUsed/1024/1024>1000){
    sendemailtoadmin("春华汽配内存应用监控提醒："+JSON.stringify(mem)+" 上报时间未--"+new Date())
    console.log("提醒管理员内存溢出")
    // logger.info("当前使用内存"+format(mem.heapUsed))
  clearInterval(memhealth)
      }
    else{
    // logger.info("当前使用内存"+format(mem.heapUsed))
    }
    }, 2000)
    

})


//定时任务 每5秒执行
schedule.scheduleJob('*/5 * * * * *', async () => {
  xm_fb()   //定时发布的项目发布更新 
  xm_ybjz() //项目应标截止更新项目状态
  xm_xbjz() //项目询价截止更新项目状态
  xm_tbkz() //项目投标截止更新项目状态
  xm_tbjz()
  xm_kb() 
  xm_pbjz() //项目评标结束更新项目状态
  // xm_lxjz() //项目遴选结束更新项目状态
  // update_gysjb()
  update_gysjb_pm() //项目为竞价结束的时候，更新竞价排名
})

//定时任务 每5秒执行
schedule.scheduleJob('*/2 * * * * *', async () => {
  // xm_fb()
  // xm_ybjz()
  // xm_tbjz()
  // xm_kb()
  // update_gysbqxj() //项目为标前询价中的时候，更新竞价状态和排名
  update_gysjb() //项目为竞价中的时候，更新竞价状态和排名
})


// // 创建计划任务  每分钟执行同步一次部门
// Schedule.scheduleJob("* * * * *", async function () {
//   await getSyndevicedata()

// });

// 获取钉钉登录二维码
app.post('/admin/sys/getDingTalkLoginUrl', async function(req, res) {
  const dingtalk = new DingTalk();
  const result = await dingtalk.getLoginQrCode();
  res.json(result);
});

// 检查钉钉登录状态
app.post('/admin/sys/checkDingTalkLogin', async function(req, res) {
  const { code } = req.body;
  const dingtalk = new DingTalk();
  const result = await dingtalk.checkLoginStatus(code);
  res.json(result);
});

// 钉钉登录回调
app.get('/admin/sys/dingtalk/callback', async function(req, res) {
  const { code, state } = req.query;
  logger.info('钉钉登录回调参数:', { code, state });

  if (!code) {
    logger.error('钉钉登录回调缺少code参数');
    res.redirect('/#/login?error=missing_code');
    return;
  }

  try {
    const dingtalk = new DingTalk();
    const result = await dingtalk.checkLoginStatus(code);
    
    if (result.success) {
      // 登录成功，重定向到前端页面并带上授权码
      res.redirect(`/#/login?code=${code}`);
    } else {
      // 登录失败，重定向到错误页面
      logger.error('钉钉登录失败:', result.message);
      res.redirect(`/#/login?error=${encodeURIComponent(result.message)}`);
    }
  } catch (error) {
    logger.error('处理钉钉登录回调失败:', error);
    res.redirect('/#/login?error=server_error');
  }
});



